package com.utils.parsetxt.xml.icsr.controller;

import com.alibaba.fastjson.JSON;
import com.utils.parsetxt.xml.icsr.bean.IcsrDTO;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IcsrController {

    /**
     * 首页
     * @return
     */
    @GetMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping("/upload")
    public String uploadFile(@RequestParam("iFile") MultipartFile file, Model model){
        if(file.isEmpty()){
            model.addAttribute("msg","上传失败，请选择文件！");
        } else {
            try {
                IcsrDTO icsr = new IcsrDTO();
                // TODO 这里的命名空间是难点
                DocumentFactory factory = DocumentFactory.getInstance();
                Map<String, String> nsMap = new HashMap<>();
                nsMap.put("n", "urn:hl7-org:v3");
                factory.setXPathNamespaceURIs(nsMap);

                SAXReader reader = new SAXReader();
                Document document =reader.read(file.getInputStream());
                XPath xPath = factory.createXPath("/n:MCCI_IN200100UV01");
                Node root = xPath.selectSingleNode(document);
                Node investigationEventNode = root.selectSingleNode("n:PORR_IN049016UV/n:controlActProcess/n:subject/n:investigationEvent");
                Node codeNode = investigationEventNode.selectSingleNode("n:id[@root='2.16.840.1.113883.3.989.2.1.3.1']");

                String code = ((Element)codeNode).attributeValue("extension");
                icsr.setCode(code);

                Node nameNode = investigationEventNode.selectSingleNode("n:component/n:adverseEventAssessment/n:subject1/n:primaryRole/n:player1/n:name");
                icsr.setName(nameNode.getText());
                Node birthdayNode = investigationEventNode.selectSingleNode("n:component/n:adverseEventAssessment/n:subject1/n:primaryRole/n:player1/n:birthTime");
                icsr.setBirthday(LocalDate.parse(((Element)birthdayNode).attributeValue("value"), DateTimeFormatter.ofPattern("yyyyMMdd")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

                List<Node> sourceNodes = investigationEventNode.selectNodes("n:component/n:adverseEventAssessment/n:subject1/n:primaryRole/n:subjectOf2/n:observation/n:code[@code='29']");
                StringBuilder source = new StringBuilder();
                for (Node sourceNode : sourceNodes) {
                    source.append(sourceNode.getParent().selectSingleNode("n:value/n:originalText").getText()).append(",");
                }
                icsr.setSource(source.substring(0, source.length()-1));

                Node drugNode = investigationEventNode.selectSingleNode("n:component/n:adverseEventAssessment/n:subject1/n:primaryRole/n:subjectOf2/n:organizer/n:code[@code='4']");
                List<Node> nodes = drugNode.getParent().selectNodes("n:component/n:substanceAdministration/n:consumable/n:instanceOfKind/n:kindOfProduct/n:name");
                StringBuilder drug = new StringBuilder();
                for (Node node : nodes) {
                    drug.append(node.getText()).append(",");
                }
                icsr.setDrug(drug.substring(0, drug.length()-1));

                System.out.println(JSON.toJSON(icsr));
                List<IcsrDTO> list = new ArrayList<>();
                list.add(icsr);
                list.add(new IcsrDTO("1","test1"));
                list.add(new IcsrDTO("2","test2"));
                model.addAttribute("icsrs",list);
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
                model.addAttribute("msg","文件上传失败！");
            }
        }
        return "index";
    }

}
